# -*- coding: utf-8 -*-
# @Time : 2021/05/17/
# @Author : ricky
# @File : base.py
# @Software: vscode
"""
关键字修改类基类
"""
import os
from shutil import move
from loguru import logger


class BaseCore:

    DEFAULT_ENCODING = 'utf-8'
    BAT_FILE_ENCODING = 'ANSI'
    """
    初始化参数:
        param (AlterParam): 修改参数
        configdict (dict): 配置字典
        callback (function): 回调方法

    """
    def __init__(self, param, configdict, callback):

        self.context = param.context
        self.targetdir = param.targetdir
        self.sitename = param.sitename
        self.packagename = param.packagename
        self.projectdirname = param.projectdirname
        self.projectname = param.projectname
        self.artifactid = param.artifactid
        self.groupid = param.groupid
        self.configdict = configdict
        self.callback = callback
        self.exceptions = []

    def start(self):
        """开始方法"""
        pass

    def messagehandle(self, message):
        """
        消息处理

        参数:
            message (str): 消息
        """
        if hasattr(self.callback, '__call__'):
            self.callback(message)

    def exceptionhandle(self, message):
        """
        异常处理

        参数:
            message (str): 消息
        """
        self.exceptions.append(str(len(self.exceptions) + 1) + "." + message)
        logger.error(message)

    def move_dir(self, old_dir, new_dir):
        """
        移动目录
        
        参数:
            old_dir (str): 旧目录
            new_dir (str): 新目录
        """
        for temp_path in os.listdir(old_dir):
            filepath = new_dir + os.path.sep + temp_path
            oldpath = old_dir + os.path.sep + temp_path
            if os.path.isdir(oldpath):
                os.mkdir(filepath)
                self.move_dir(oldpath, filepath)
            if os.path.isfile(oldpath):
                move(oldpath, filepath)

    def get_encoding(self, filename):
        """
        返回文件编码
        
        参数:
            filename (str): 文件名（带后缀）
        """
        if filename.endswith('bat'):
            return self.BAT_FILE_ENCODING
        return self.DEFAULT_ENCODING